#include <iostream>
#include <SDL.h>
#include <QApplication>
#include <memory>
#include <thread>
#undef main
using namespace std;
int main(int argc, char *argv[])
{
    int w = 800, h = 600;
    cout << "SDL_Init" << endl;
    // 初始化SDL video库
    if (SDL_Init(SDL_INIT_VIDEO) != 0)
    {
        cout << "SDL_Init Error: " << SDL_GetError() << endl;
        return -1;
    }
    // 生成窗口
    auto screen = SDL_CreateWindow("SDL2-test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w, h, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
    if (!screen)
    {
        cout << "SDL_CreateWindow Error: " << SDL_GetError() << endl;
        return -1;
    }
    // 创建渲染器
    auto renderer = SDL_CreateRenderer(screen, -1, SDL_RENDERER_ACCELERATED);
    if (!renderer)
    {
        cout << "SDL_CreateRenderer Error: " << SDL_GetError() << endl;
        return -1;
    }
    // 创建纹理
    auto texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, w, h);
    if (!texture)
    {
        cout << "SDL_CreateTexture Error: " << SDL_GetError() << endl;
        return -1;
    }
    shared_ptr<uint8_t> rgb(new uint8_t[w * h * 4]);
    memset(rgb.get(), 0xff, w * h * 4);
    auto r = rgb.get();
    uint8_t tmp = 255;
    for (;;)
    {
        SDL_Event event;
        int ret = SDL_WaitEventTimeout(&event, 10);
        if (event.type == SDL_QUIT)
        {
            SDL_DestroyWindow(screen);
            break;
        }
        tmp--;
        for (int j = 0; j < h; j++)
        {
            int b = j * w * 4;
            for (int i = 0; i < w * 4; i += 4)
            {
                r[b + i] = 0;       // B
                r[b + i + 1] = 0;   // G
                r[b + i + 2] = tmp; // R
                r[b + i + 3] = 0;   // A
            }
        }
        // 将内存写入纹理
        SDL_UpdateTexture(texture, nullptr, rgb.get(), w * 4);
        // 渲染纹理
        SDL_RenderClear(renderer);
        SDL_Rect rect = {0, 0, w, h};
        SDL_RenderCopy(renderer, texture, nullptr, &rect);
        SDL_RenderPresent(renderer);
    }
    return 0;
}